import React, { Component } from 'react';
import { Affix, Button, Form, message } from 'antd';
import { connect } from 'react-redux';
import { getDefaultSetOfBook, messages } from 'share/common';
import Priority from 'components/template/priority/priority';
import 'styles/expense-reimbursement-control/mileage-subsidy/new-mileage-subsidy.scss';
import { formData, mileageRange } from 'containers/expense-reimbursement-control/new-mileage-subsidy/dataSources';
import mileageService
  from 'containers/expense-reimbursement-control/new-mileage-subsidy/mileage-service';
import { permission } from 'containers/finance-setting/permisson';

@connect(mapStateToProps)
@permission
class NewMode extends Component {

  static  propTypes = {};

  state = {
    formList: {
      'enabled': { initData: true, valuePropName: 'checked' },
      'mileageUnit': { initData: 'KM' },
      'unitPriceRange': { initData: 10 },
      'defaultMileageValue': { initData: 'maximum' },
      'mileageModifyRange': { initData: '' },
      'editable': { initData: true },
      'manyInvoice': { initData: '1' },
      'addrModifyRange': {},
      'drivingPlanValue': { initData: 10 },
      'mileageCreateModes': {initData: ['POSITIONING', 'NAVIGATION']}
    },
    priority: void 0,
    submitLoading: false,
  };

  componentWillMount() {
    this.handleInitPriority();
  }

  componentDidMount() {
    this.handleInit();
  }

  handleInitPriority() {
    let { priority = {} } = this.state;
    const { params: { unitPriceOptId, stepOptId, levelCode, levelOrgId, levelOrgName, companies, companyNameList, setOfBook } } = this.props;

    if (!unitPriceOptId && !stepOptId) {
      this.setState({
        priority: {
          levelCode: 'SET_OF_BOOK',
          levelOrgId: setOfBook.id,
          levelOrgName: setOfBook.name
        }
      });
      return;
    }

    priority.distribution = {};
    companies && (priority.distribution.companies = companies.map((item, index) => {
      return {
        name: companyNameList[index],
        id: item
      };
    }));
    priority = { ...priority, levelCode, levelOrgId, levelOrgName };
    this.setState({ priority });

  }

  handleInit = () => {
    let { formList } = this.state;
    const { params, params: { unitPriceOptId, stepOptId, mode } } = this.props;
    if (mode === 'addUnitMode') {
      delete formList.manyInvoice;
    }

    if (mode === 'addLadderMode') {
      delete formList.editable;
      delete formList.unitPriceRange;
    }

    if (!unitPriceOptId && !stepOptId) {
      this.setState({ formList });
      return;
    }

    Object.keys(formList)
      .map(item => {
        if (params[item] !== null && params[item] !== void 0) {
          formList[item].initData = params[item];
        }
      });
    this.setState({ formList });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { priority, priority: { distribution } } = this.state;
    const { params: { mode }, params } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (!priority || !priority.levelCode) {
          message.error(messages('expense-12.key153')/*请选择所属组织*/);
          return;
        }
        if(priority && (priority.levelCode === 'SET_OF_BOOK') && priority.distribution && priority.distribution.companies &&
          !priority.distribution.companies.length) {
          message.error(messages('expense-12.key150')/*请选择启用公司*/);
          return;
        }

        this.setState({ submitLoading: true });
        distribution && distribution.companies && (priority.companies = distribution.companies.map(item => item.id));
        delete priority.distribution;
        delete params.companies;
        console.log('handleSubmit', { ...params, ...values, ...priority })
        mileageService[mode]({ ...params, ...values, ...priority })
          .then(() => {
            message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
            this.props.close('mode');
          })
          .finally(() => {
            this.setState({ submitLoading: false });
          });
      }
    });
  };

  handleCancel = () => {
    this.props.close(false);
  };

  handlePriority = (priority) => {
    this.setState({ priority });
  };

  handleRangeChange = () => {
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ addrModifyRange: void 0 });
  };

  handleMileageUnit = (key, item) => {
    const { form: { getFieldValue } } = this.props;
    const mileageUnit = getFieldValue('mileageUnit');
    if (key === 'mileageUnit') {
      item.params = {};
      item.params.onChange = this.handleRangeChange;
      return item;
    }
    if(!mileageUnit || key!== 'addrModifyRange') return item;
    item.params.max = mileageRange[mileageUnit].range;
    item.params.formatter = value => `${value}${mileageUnit}`;
    item.params.parser = value => value.replace(mileageRange[mileageUnit].reg, '');
    item.extra = messages('expense-12.key155',{arg1: mileageRange[mileageUnit].name,arg2: mileageRange[mileageUnit].range})/*配置地址修改限制，仅可修改为原定位周围N{arg1}（可为空，或范围为0-{arg2}的整数，为空时则可随意修改位置，为0则不允许修改定位）*/
    return item;
  };

  renderForm = () => {

    const { formList, submitLoading, priority } = this.state;
    const {
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
      params: { readOnly, unitPriceOptId, stepOptId }
    } = this.props;
    const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 10, offset: 0 } };

    const formArray = Object.keys(formList)
      .map(item => {
        const middleForm = this.handleMileageUnit(item, formData[item]);
        const { name, child, params = {}, required, component, extra } = middleForm;
        params.disabled = this.isReadOnly() || readOnly;
        if (item === 'mileageModifyRange') {
          if (['travel', 'travel_priority'].includes(getFieldValue('defaultMileageValue'))) {
            params.disabled = true;
            if (getFieldValue('mileageModifyRange') || getFieldValue('mileageModifyRange') === 0) {
              setFieldsValue({ mileageModifyRange: undefined });
            }
          }
        }
        const Element = React.createElement(component, params, child);
        return (
          <Form.Item extra={extra} label={name}>
            {
              getFieldDecorator(item, {
                rules: [{
                  required: !!required,
                  message: middleForm.requireErrorMessage || messages('expense-12.key156')/*请输入temp2*/ + name
                }],
                initialValue: formList[item].initData,
                valuePropName: formList[item].valuePropName || 'value'
              })(Element)
            }
          </Form.Item>
        );
      });
    formArray.splice(1, 0, (
      <Priority
        top={'SET_OF_BOOK'}
        single={false}
        onChange={this.handlePriority}
        disabled={this.isReadOnly() || readOnly}
        companyProps={{
          disabled: (readOnly || !!unitPriceOptId || !!stepOptId)
        }}
        disabledTop={!!unitPriceOptId || !!stepOptId}
        defaultValue={priority}
        formItemLayout={formItemLayout}
        required
      />));

    return (
      <Form onSubmit={this.handleSubmit} >
        {
          formArray
        }
        <div className="slide-footer">
          <Button
            type="primary"
            loading={submitLoading}
            disabled={readOnly || this.isReadOnly()}
            htmlType="submit"
           >
            {messages('common.save')/*保存*/}
          </Button>
          <Button
            onClick={this.handleCancel}
            disabled={readOnly || this.isReadOnly()}
            className="new-unit-cancel"
          >
            {messages('common.cancel')/*取消*/}
          </Button>
        </div>
      </Form>
    );
  };

  render() {
    return (
      <section className='new-unit new-form'>
        {
          this.renderForm()
        }
      </section>
    );
  }
}

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
  };
}

const WrappedNewUnit = Form.create()(NewMode);

export default WrappedNewUnit;
